from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length, Email
from app.models.user import User
from flask_login import current_user

class EditProfileForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(1, 64)])
    email = StringField('邮箱', validators=[DataRequired(), Length(1, 64), Email()])
    about_me = TextAreaField('个人简介')
    avatar = FileField('更换头像', validators=[FileAllowed(['jpg', 'png', 'jpeg'], '只允许上传jpg或png格式的图片')])
    submit = SubmitField('保存修改')
    
    def validate_email(self, field):
        if field.data != current_user.email and \
                User.query.filter_by(email=field.data).first():
            raise ValidationError('该邮箱已被注册')
    
    def validate_username(self, field):
        if field.data != current_user.username and \
                User.query.filter_by(username=field.data).first():
            raise ValidationError('该用户名已被使用') 